package com.scalar.chiptrack.operations.finishedGoods.actionCommands;

import com.scalar.chiptrack.ChipTrackExtendedAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.finishedGoods.forms.FinishedGoodsEntryForm;
import com.scalar.chiptrack.operations.finishedGoods.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.finishedGoods.EquivalentPartNumber;
import com.scalar.chiptrack.operations.finishedGoods.FinishedGoodsHelper;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.processtypesetup.dao.ProcessTypeSetupDAO;
import com.scalar.ScalarException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * User: Murali Krishna Yengala
 * Date: May 31, 2005
 * Time: 9:48:45 AM
 */
public class FinishedGoodsModifyConfirmCommand extends ChipTrackExtendedAction{

        public ActionForward executeRequest( ActionMapping mapping,
                                             ActionForm form,
                                             HttpServletRequest request,
                                             HttpServletResponse response) throws Exception
        {
            FinishedGoodsEntryForm finishedGoodsEntryForm = ( FinishedGoodsEntryForm ) form;
            HashMap errors              = ( HashMap ) request.getAttribute( ERROR_MESSAGES );
            HashMap info                = ( HashMap ) request.getAttribute( INFO_MESSAGES );

            int baseProductIdI = finishedGoodsEntryForm.getBaseProductIdI();
            FinishedGoodsHelper.setFgiProducts( baseProductIdI, request, errors, info);
            FinishedGoodsHelper.setCustomers( request, errors );
            finishedGoodsEntryForm.setVendorList( FinishedGoodsHelper.getVendorLocations( request));
            request.setAttribute( "units", ProcessTypeSetupDAO.getUnitsOfMesurment() );
            request.setAttribute( "algorithmList", FinishedGoodsDAO.loadAlgorithmList());

            int processStepIdI = -1;
            try
            {
                String processStepIdS = finishedGoodsEntryForm.getProcessStepId();
                processStepIdS = (processStepIdS == null ? "" : processStepIdS.trim());
                processStepIdI = Integer.parseInt( processStepIdS);
            }
            catch( NumberFormatException e)
            {
                errors.put(ERROR_INTERNAL_SERVER_ERROR,"Invalid Finished Goods");
                request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                return mapping.findForward("editFg");
            }
            String partNumberS = finishedGoodsEntryForm.getFinishedGoodsPartNo();
            try
            {
                boolean partNoPresent = FinishedGoodsDAO.checkForDuplicateValueInProductTable( partNumberS, processStepIdI, 1);
                boolean partNoPresentInMktgPartNo = FinishedGoodsDAO.checkForDuplicateValueInProductTable( partNumberS, processStepIdI, 2);
                if ( partNoPresent || partNoPresentInMktgPartNo )
                {
                    errors.put ( "OPN / Mktg Part Number = "+partNumberS, " Already Exists" );
                    request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                    return mapping.findForward("editFg");
                }
            }
            catch( ScalarException e)
            {
                e.printStackTrace();
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, "" );
                request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                return mapping.findForward("editFg");
            }
            String[] partNumbers = new String[ 1 ];
            partNumbers[ 0 ] = partNumberS;
            try
            {
                String dupNames = ProductDao.checkDupInProductMapTable ( partNumbers , processStepIdI , Constants.LOCATION_TYPE_FINISHED_GOODS );
                if( dupNames != null && dupNames.length () > 0 )
                {
                    errors.put ( "OPN / Mktg Part Number = "+partNumberS, " Already Exists" );
                    request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                    return mapping.findForward("editFg");
                }
            }
            catch( ScalarException e)
            {
                e.printStackTrace();
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, "" );
                request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                return mapping.findForward("editFg");
            }

            String programCodeS = finishedGoodsEntryForm.getProgramCode();
            programCodeS = (programCodeS == null ? "" : programCodeS.trim());
            try
            {
                // processStepId for 3rd parameter, because this is an existing finished good
                ArrayList fgiPartsAndCustomers = FinishedGoodsDAO.checkForProgramCodeDuplicates(programCodeS, finishedGoodsEntryForm.getCustomerIds(), finishedGoodsEntryForm.getProcessStepIdI(), finishedGoodsEntryForm.getFgiProcessStepIds());
                if( fgiPartsAndCustomers != null  && fgiPartsAndCustomers.size() > 0)
                {
                    StringBuffer errorMsg = new StringBuffer("Already exists for the following Customer(s) and Blank FGI part Number(s)<tr class='NArialL'><td colspan='2'><font color='red'>");
                    for( int i = 0; i < fgiPartsAndCustomers.size(); i++)
                    {
                        errorMsg.append( "<li>"+fgiPartsAndCustomers.get(i) );
                    }
                    errors.put("Program Code = "+programCodeS, errorMsg.toString()+"</font></td></tr>");
                    request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                    return mapping.findForward("editFg");
                }
            }
            catch( ScalarException e)
            {
                e.printStackTrace();
                errors.put ( ERROR_INTERNAL_SERVER_ERROR, "" );
                request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                return mapping.findForward("editFg");
            }

            ArrayList dupPartNosArrayList = finishedGoodsEntryForm.getEquivalentPartNosList();
            if( dupPartNosArrayList != null)
            {
                Iterator dupPartsIterator = dupPartNosArrayList.iterator();
                while( dupPartsIterator.hasNext() )
                {
                    EquivalentPartNumber dupPartNumber = ( EquivalentPartNumber) dupPartsIterator.next();
                    String partNo = dupPartNumber.getPartNo();
                    if(partNo==null ||  (partNo != null && "".equals(partNo.trim())))
                    {
                        dupPartsIterator.remove();
                    }
                }
                if( dupPartNosArrayList.size() == 0)
                {
                    finishedGoodsEntryForm.setEquivalentPartNosList( null);
                }
                else
                {
                    String[] dupPartNosArray = new String[dupPartNosArrayList.size()];
                    dupPartsIterator = null;
                    dupPartsIterator = dupPartNosArrayList.iterator();
                    int idx = 0;
                    while( dupPartsIterator.hasNext() )
                    {
                        EquivalentPartNumber dupPartNumber = ( EquivalentPartNumber) dupPartsIterator.next();
                        String partNo = dupPartNumber.getPartNo();
                        if( partNo != null)
                        {
                            dupPartNosArray[idx++] = partNo.trim();
                        }
                    }

                    try
                    {
                        String dupNames = ProductDao.checkDupInProductMapTable ( dupPartNosArray , processStepIdI , Constants.LOCATION_TYPE_FINISHED_GOODS );
                        if( dupNames != null && dupNames.length () > 0 )
                        {
                            errors.put ( "Equivalent Part Numbers = "+dupNames, " Already Exists" );
                            request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                            return mapping.findForward("editFg");
                        }
                    }
                    catch( Exception e)
                    {
                        e.printStackTrace();
                        errors.put ( ERROR_INTERNAL_SERVER_ERROR, "" );
                        request.setAttribute( SessionKeys.ERROR_MESSAGES, errors);
                        return mapping.findForward("editFg");
                    }
                }
            }
            request.setAttribute( SessionKeys.INFO_MESSAGES, info);
            request.setAttribute( SessionKeys.ERROR_MESSAGES, info);
            return mapping.findForward("view");
        }
}
